import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'


// 基础地址与代理对齐
axios.defaults.baseURL = '/api'

// 将 axios 挂到原型，组件里才能 this.$axios
Vue.prototype.$axios = axios

Vue.config.productionTip = false


// axios前置拦截器
axios.interceptors.request.use(config => {
  //在所有请求中加入认证token
  let token = window.sessionStorage.getItem('token')
  if (token != null) {
    config.headers['Authorization'] = token
  }
  return config
}, error => {
  Promise.reject(error)
})

//axios后置拦截器
axios.interceptors.response.use(response => {
  //当token快过期时，后台会进行延期处理，生成新的token，前台需更换新的token
  let refToken = response.headers['x-token']
  if (refToken) {
    //如果有新的token，则替换原有token
    window.sessionStorage.setItem('token', refToken);
  }
  console.log("后置拦截", response)
  return response
}, error => {
  console.log('后置拦截错误', error.response.data)
  //统一处理服务端的报错
  if (error.response) {
    alert(error.response.data.msg)
    if (error.response.status == 401) {
      window.localStorage.removeItem('token')
      window.localStorage.removeItem('userId')
      window.localStorage.removeItem('userType')
      // alert(error.response.data)
      if (router.currentRoute.path !== '/login') {
        alert('请登录！')
        router.push('/login')
      }
      // return Promise.resolve({ data: {} })
      // return Promise.reject(error)
      return Promise.resolve({ data: {} })
    }
  }
  return Promise.reject(error);
})



console.log('✅ main.js 已执行');
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

